package by.blog.web.servlets;

import by.blog.dao.beans.Film;
import by.blog.dao.dao.factory.MysqlDaoFactory;
import by.blog.service.CategoryService;
import by.blog.service.FilmService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * web.xml: /main.jsp
 * This class generate connection to DB,
 * create list of all categories and
 * list of all films and put them into ServletContext
 * -->/jsp/main
 */
public class Generator extends HttpServlet {

    private static final long serialVersionUID = 1L;
    CategoryService categoryService;

    /**
     * Method realize connection to DB,
     * create list of all categories
     * @throws ServletException
     */
    @Override
    public void init() throws ServletException {
        super.init();
        try {
            MysqlDaoFactory daoFactory = MysqlDaoFactory.getInstance();
        }
        catch (Exception e) {

        }
        categoryService = new CategoryService();
       categoryService.setListOfAllCategories(categoryService.readAllUnits());
    }

    /**
     * web.xml: /main.jsp
     * This method put list of all categories into ServletContext
     * and list of all films to request to create menu
     * -->/jsp/main.jsp
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html; charset=UTF-8");
        response.setHeader("Cache-Control","no-cache");
        request.setCharacterEncoding("UTF-8");

        FilmService filmService = new FilmService();
        List<Film> filmList = filmService.readAllUnits();

        ServletContext servletContext = getServletContext();
        servletContext.setAttribute("allCategories", categoryService.getListOfAllCategories());
        request.setAttribute("allFilms", filmList);

        RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/jsp/main.jsp");
        dispatcher.forward(request, response);
    }

        @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


}
